﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SimpleBlog.Models;
using SimpleBlog.Helpers;
using SimpleBlog.Infrastructure.Repositories;
using SimpleBlog.Areas.Admin.ViewModels;

namespace SimpleBlog.Areas.Admin.Controllers
{
    public class PostController : Controller
    {
        public static string SUMMARY_SEPARATOR = "<hr />";

        IPostRepository _postRepository;
        ITagRepository _tagRepository;

        public PostController(IPostRepository postRepository, ITagRepository tagRepository)
        {
            _postRepository = postRepository;
            _tagRepository = tagRepository;
        }

        [Authorize]
        public ActionResult Create()
        {
            return RedirectToAction("Edit", new { id = 0 });
            
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            if (id == 0)
            {
                return View("Edit", new PostEditViewModel()
                {
                    PostId = 0
                });
            }

            var selectedPost = _postRepository.FindById(id);
            if (selectedPost == null)
                throw new HttpException(404, "Post not found. Please enter a valid Id");

            var text = selectedPost.Text.Insert(selectedPost.Summary.Length, SUMMARY_SEPARATOR);

            var model = new PostEditViewModel()
            {
                PostId = selectedPost.PostId,
                Title = selectedPost.Title,
                EncodedTitle = selectedPost.EncodedTitle,
                Text = text,
                Tags = selectedPost.Tags.Select(x => x.Name).Stringfy()
            };
            return View(model);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Edit(PostEditViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                //The PostEditViewModel has validated the input, and is sure it has the SUMMARY_SEPARATOR 
                var splitted = viewModel.Text.Split(new string[] { SUMMARY_SEPARATOR }, StringSplitOptions.None);

                //Create or get the post
                Post actualPost;
                if (viewModel.PostId == 0)
                {
                    actualPost = new Post();
                    actualPost.Created = DateTime.UtcNow;
                    actualPost.Creator = SessionHelper.Authenticated;
                    actualPost.EncodedTitle = EncoderHelper.EncodeTitle(viewModel.Title);
                    actualPost.Title = viewModel.Title;
                }
                else
                {
                    actualPost = _postRepository.FindById(viewModel.PostId);
                    if (actualPost.Creator.UserId != SessionHelper.Authenticated.UserId)
                        actualPost.Creator = SessionHelper.Authenticated;
                    if (actualPost.Title != viewModel.Title)
                    {
                        actualPost.EncodedTitle = EncoderHelper.EncodeTitle(viewModel.Title);
                        actualPost.Title = viewModel.Title;
                    }
                }

                //Update text and summary
                actualPost.Summary = splitted[0];
                actualPost.Text = splitted[0] + splitted[1];
                //Update tags
                if (!string.IsNullOrWhiteSpace(viewModel.Tags))
                {
                    var tags = viewModel.Tags
                        .Split(',')
                        .Where(x => !string.IsNullOrWhiteSpace(x))
                        .Select(x => x.ToLowerInvariant().Trim());
                    _tagRepository.SetTags(actualPost, tags);
                }
                //Add or Update post
                if (viewModel.PostId != 0)
                    _postRepository.Modify(actualPost);
                else
                    _postRepository.Add(actualPost);

                if (actualPost.PostId != 0)
                {
                    return RedirectToAction("Index", "Post", new { area = string.Empty, name = actualPost.EncodedTitle });
                }
                else
                {
                    ModelState.AddModelError("", "Error creating the new post. Try again.");
                }
            }

            return View(viewModel);
        }

    }
}
